﻿using System;
using System.Windows.Forms;

namespace RdpClient
{
    public class RdpTabPage : TabPage
    {
        AxMSTSCLib.AxMsRdpClient9 rdpc = null;
        protected override void OnCreateControl()
        {
            rdpc = new AxMSTSCLib.AxMsRdpClient9();
            rdpc.OnDisconnected += new AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEventHandler(rdpc_OnDisconnected);
            this.Controls.Add(rdpc);
            rdpc.Dock = DockStyle.Fill;
            base.OnCreateControl();
        }

        void rdpc_OnDisconnected(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e)
        {
            ((TabControl)this.Parent).TabPages.Remove(this);
        }

        public void Disconnect()
        {
            try
            {
                if (rdpc.Connected == 1)
                {
                    rdpc.Disconnect();
                }
            }
            catch (Exception) { }
        }

        private void SetRdpClientProperties(RdpInfo info)
        {
            rdpc.Server = info.MachineName;
            rdpc.UserName = info.UserName;
            rdpc.Domain = "";
            rdpc.AdvancedSettings9.RDPPort = info.RdpPort;
            rdpc.AdvancedSettings9.ClearTextPassword = info.Password;
            rdpc.AdvancedSettings9.RedirectDrives = true;
            rdpc.AdvancedSettings9.RedirectPrinters = true;
            rdpc.AdvancedSettings9.RedirectSmartCards = true;
            rdpc.AdvancedSettings9.ConnectToServerConsole = true;
            rdpc.ColorDepth = 32;
            rdpc.Dock = DockStyle.Fill;
        }

        public void Connect(RdpInfo info)
        {
            SetRdpClientProperties(info);
            rdpc.Connect();
        }
    }
    public class RdpInfos
    {
        public RdpInfo[] Items { get;set; }
    }
    public class RdpInfo
    {
        public string AliasName { get; set; }
        public string MachineName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public int RdpPort { get; set; }
        public bool ShareDiskDrives { get; set; }
        public bool SharePrinters { get; set; }
    }
}